<template>
  <div class="login-bg">
    <div class="form-btn">
      <h1>在线发卡平台</h1>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="登录" name="first" class="pad-box">
          <el-form :model="loginForm" :rules="formRules" ref="loginFormRef" label-position="right"
                   status-icon>
            <el-form-item label="账号" prop="username">
              <el-input v-model="loginForm.username" placeholder="请输入账号" :maxlength="8" show-word-limit/>
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input v-model="loginForm.password" placeholder="请输入密码" type="password" show-password/>
            </el-form-item>

            <el-form-item label="验证码" prop="userCode">
              <el-input v-model="loginForm.userCode" placeholder="请输入验证码" style="width: 60%;" size="small"
                        @keyup.enter="login(loginFormRef)"/>
              <el-image style="width: 40%;" :src="codeUrl" fit="cover" @click="changCode"/>
            </el-form-item>

            <el-button type="primary" size="large" class="subBtn" @click="login(loginFormRef)">点击登录</el-button>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="注册" name="second" class="pad-top">
          <el-form :model="risForm" :rules="risRules" ref="risFormRef" label-position="right"
                   status-icon>
            <el-form-item label="邀请码" prop="usercode">
              <el-input v-model="risForm.usercode" placeholder="请输入邀请码"/>
            </el-form-item>
            <el-form-item label="手机号" prop="userphone">
              <el-input v-model="risForm.userphone" placeholder="请输入手机号"/>
            </el-form-item>
            <el-form-item label="账号" prop="username">
              <el-input v-model="risForm.username" placeholder="请输入账号" :maxlength="8" show-word-limit/>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="risForm.password" placeholder="请输入密码" type="password" show-password/>
            </el-form-item>
            <el-form-item label="验证码" prop="userCode">
              <el-input v-model="risForm.userCode" placeholder="请输入验证码" style="width: 60%;" size="small"
                        @keyup.enter="saveRis(risFormRef)"/>
              <el-image style="width: 40%;" :src="codeUrl" fit="cover" @click="changCode"/>
            </el-form-item>
            <el-button type="danger" size="large" class="RisBtn" @click="saveRis(risFormRef)">点击注册</el-button>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import {validatorUsername, validatorPwd, validatorPhone} from "@/utils/globalVariables"
import {ref, reactive, onMounted} from "vue"
import {ElMessage} from 'element-plus'
import router from "@/router"
import api from "@/api"
import store from '@/store/index'

onMounted(() => {
  codeUrl.value = store.state.baseUrl + codeUrl.value
})
const codeUrl = ref("/verification")
const changCode = () => {
  codeUrl.value = codeUrl.value + "?" + Math.random();
}

const activeName = ref('first')

const loginForm = reactive({
  userCode: '',
  username: '',
  password: '',
})
const risForm = reactive({
  usercode: '',
  userphone: '',
  username: '',
  password: '',
  userCode: "",
})

const formRules = {
  username: [
    {required: true, message: '用户名不能为空', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
  ],
  userCode: [
    {required: true, message: '验证码不能为空', trigger: 'blur'},
  ],
}
const risRules = {
  usercode: [
    {required: true, message: '邀请码不能为空', trigger: 'change'},
  ],
  userphone: [
    {required: true, message: '手机号不能为空', trigger: 'change'},
    {validator: validatorPhone, triger: 'blur'}
  ],
  username: [
    {required: true, message: '用户名不能为空', trigger: 'change'},
    {min: 4, max: 8, message: '账号长度为 6~14 个字符', trigger: 'change'},
    {validator: validatorUsername, triger: 'blur'}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'change'},
    {min: 6, max: 14, message: '密码长度为 6~14 个字符', trigger: 'change'},
    {validator: validatorPwd, triger: 'blur'}
  ],
  userCode: [
    {required: true, message: '验证码不能为空', trigger: 'change'},
  ],
}

// TODO 表单整体校验 + 登录
const loginFormRef = ref(null)
const login = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      checkLogin(loginForm)
    } else {
      ElMessage.error('请按要求填写')
    }
  })
}

const risFormRef = ref(null)
const saveRis = () => {
  risFormRef.value.validate((valid) => {
    if (valid) {
      checkRis(risForm)
    } else {
      ElMessage.error('请按要求填写')
    }
  })
}
const checkRis = async (user) => {
  try {
    const response = await api.insertUser(user)
    if (response.code === 1) {
      ElMessage.error(response.message)
    } else {
      ElMessage.success('注册成功，请联系客服审核！')
    }
  } catch (error) {
    throw new Error('Failed to fetch rating data')
  }
}
const checkLogin = async (user) => {
  try {
    const response = await api.login(user)
    if (response.code === 1) {
      ElMessage.error(response.message)
    } else {
      store.commit('setToken', response.obj.token)
      store.commit('setUserInfo', response.obj)
      router.push('/home')

      ElMessage.success('登录成功')
    }
  } catch (error) {
    throw new Error('Failed to fetch rating data')
  }
}
</script>

<style scoped lang="less">
.demo-tabs {
  .pad-box {
    padding: 50px 10% 0 10%;
  }

  .pad-top {
    padding: 20px 10% 0 10%;
  }
}

/deep/ .el-tabs__item {
  font-size: 20px;
}

.login-bg {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: hidden;
  padding-top: 3%;
  background: #efefef;

  h1 {
    color: #248bee;
    margin-bottom: 35px;
  }

  .form-btn {
    box-shadow: 0px 0px 12px rgb(0 0 0 / 24%);
    background: #ffffff;
    width: 30%;
    height: 60%;
    padding: 50px 5%;
    margin: 0 auto;

    .el-form-item {
      margin-bottom: 26px;
    }

    .subBtn {
      width: 100%;
      margin-top: 100px;
    }

    .RisBtn {
      width: 100%;
      margin-top: 20px;
    }

    .el-input {
      width: 100%;
    }

    /deep/ .el-input__inner {
      font-size: 16px;
      height: 35px;
    }
  }
}
@media screen and (max-width: 720px) {
  .login-bg {
    .demo-tabs {
      .pad-box {
        padding: 50px 2% 0 2%;
      }

      .pad-top {
        padding: 20px 4% 0 4%;
      }
    }
    .form-btn {
      box-shadow: 0px 0px 12px rgb(0 0 0 / 24%);
      background: #ffffff;
      width: 80%;
      height: 80%;
      padding: 50px 6%;
      margin: 0 auto;
      .el-form-item {
        margin-bottom: 40px;
      }
    }
  }
}
</style>